<template>
	<el-dialog title="角色权限设置" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" ref="dialogForm" label-width="80px" label-position="right">
			<el-tabs tab-position="top">
				<el-tab-pane label="菜单权限">
					<el-form-item label="选择菜单" prop="menuIdList">
						<el-checkbox v-model="menuConfig.expand" @change="handleTreeExpand($event, 'menu')">展开</el-checkbox>
						<el-checkbox v-model="menuConfig.checkStrictly" @change="handleTreeCheckStrictly($event, 'menu')">父子联动</el-checkbox>
						<div class="treeMain">
							<el-tree ref="menu" node-key="id" :data="menuList" :props="menuProps"
									 default-expand-all
									 :default-checked-keys="menuCheckedList"
									 :check-strictly="!menuConfig.checkStrictly"
									 empty-text="加载中，请稍候"
									 show-checkbox></el-tree>
						</div>
					</el-form-item>
				</el-tab-pane>
				<el-tab-pane label="数据权限">
					<el-form-item label="规则类型" prop="dataScope">
						<el-select v-model="form.dataScope" placeholder="请选择" @change="handleDataScopeChange">
							<el-option label="全部可见" value="1"></el-option>
							<el-option label="仅本人可见" value="2"></el-option>
							<el-option label="所在部门可见" value="3"></el-option>
							<el-option label="所在部门及子级可见" value="4"></el-option>
							<el-option label="自定义部门可见" value="5"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="选择部门" prop="deptIdList" v-show="form.dataScope==='5'">
						<el-checkbox v-model="deptConfig.expand" @change="handleTreeExpand($event, 'dept')">展开</el-checkbox>
						<el-checkbox v-model="deptConfig.checkAll" @change="handleTreeCheckAll($event, 'dept')">全选</el-checkbox>
						<el-checkbox v-model="deptConfig.checkStrictly" @change="handleTreeCheckStrictly($event, 'dept')">父子联动</el-checkbox>
						<div class="treeMain">
							<el-tree ref="dept" node-key="id" :data="deptList" :props="deptProps"
									 default-expand-all
									 :check-strictly="!deptConfig.checkStrictly"
									 empty-text="加载中，请稍候"
									 show-checkbox></el-tree>
						</div>
					</el-form-item>
				</el-tab-pane>
			</el-tabs>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button type="primary" :loading="isSaving" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
export default {
	emits: ['success', 'closed'],
	data() {
		return {
			// 表单元素控制
			visible: false,
			isSaving: false,
			// 所需数据选项
			menuConfig: {
				expand: true,
				checkAll: false,
				checkStrictly: false
			},
			menuCheckedList: [1],
			menuList: [],
			menuProps: {
				label: "title",
				children: "children",
				disabled: (node) => {
					// 禁用首页
					return node.id === 1;
				}
			},
			deptConfig: {
				expand: true,
				checkAll: false,
				checkStrictly: false
			},
			deptList: [],
			deptProps: {
				label: "deptName",
				children: "children"
			},
			// 表单数据
			form: {
				roleId: null,
				menuIdList: [],
				dataScope: "1",
				deptIdList: []
			},
			// 表单验证规则
			rules: {
				menuIdList: [
					{required: true, message: '请选择菜单', trigger: 'blur'}
				],
				dataScope: [
					{required: true, message: '请选择权限范围', trigger: 'blur'}
				]
			}
		}
	},
	mounted() {
		this.getMenu();
		this.getDept();
	},
	methods: {
		// 显示
		open() {
			this.visible = true;
			return this;
		},
		// 表单注入数据
		setData(id) {
			this.form.roleId = id;
			this.$API.manage.role.getPermission.get(this.form.roleId).then(res => {
				this.form.menuIdList = res.menuIdList;
				// 首页特殊处理
				const menuIdList = res.menuIdList;
				if (!menuIdList.includes(1)) {
					menuIdList.push(1);
				}
				this.$refs.menu.setCheckedKeys(menuIdList);

				this.form.dataScope = res.dataScope;
				this.form.deptIdList = res.deptIdList;
				this.$refs.dept.setCheckedKeys(res.deptIdList);
			});
		},
		// 加载数据
		async getMenu() {
			this.menuList = await this.$API.manage.permission.list.get();
		},
		async getDept() {
			this.deptList = await this.$API.manage.dept.list.get();
		},
		handleDataScopeChange(value) {
			if (value !== '5') {
				this.$refs.dept.setCheckedKeys([]);
			}
		},
		// 获取菜单节点数据
		getMenuAllCheckedKeys() {
			let checkedKeys = this.$refs.menu.getCheckedKeys();
			let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
			checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
			return checkedKeys;
		},
		// 获取部门节点数据
		getDeptAllCheckedKeys() {
			let checkedKeys = this.$refs.dept.getCheckedKeys();
			let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
			checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
			return checkedKeys;
		},
		// 树权限（展开/折叠）
		handleTreeExpand(value, type) {
			if (type === 'menu') {
				let treeList = this.menuList;
				for (let i = 0; i < treeList.length; i++) {
					this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
				}
			} else if (type === 'dept') {
				let treeList = this.deptList;
				for (let i = 0; i < treeList.length; i++) {
					this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
				}
			}
		},
		// 树权限（全选/全不选）
		handleTreeCheckAll(value, type) {
			if (type === 'menu') {
				this.$refs.menu.setCheckedNodes(value ? this.menuList : []);
			} else if (type === 'dept') {
				this.$refs.dept.setCheckedNodes(value ? this.deptList : []);
			}
		},
		// 树权限（父子联动）
		handleTreeCheckStrictly(value, type) {
			if (type === 'menu') {
				this.menuConfig.checkStrictly = !!value;
			} else if (type === 'dept') {
				this.deptConfig.checkStrictly = !!value;
			}
		},
		// 表单提交
		submit() {
			this.isSaving = true;
			this.form.menuIdList = this.getMenuAllCheckedKeys();
			this.form.deptIdList = this.getDeptAllCheckedKeys();
			this.$API.manage.role.savePermission.post(this.form).then(() => {
				this.$emit('success');
				this.visible = false;
				this.$message.success("保存成功");
			}).catch(() => {
				this.isSaving = false;
			});
		}
	}
}
</script>

<style scoped>
.treeMain {
	width: 100%;
	height: 240px;
	overflow: auto;
	border: 1px solid #dcdfe6;
	margin-bottom: 10px;
}
</style>
